<template>
    <div id="lzx_container">
        <div id="modelView"></div>
        <div id="side2D">
            <div class="item2D">
                <div class="title" v-if="!isEdit">
                    <span>图纸</span>
                </div>
                <div class="content" v-if="!isEdit">
                    <ul class="drawinglist">
                        <li v-for="(items, i) in drawingFrame" :key="i">
                            <div>{{ items.comment }}</div>
                            <div v-for="(item, j) in items.model" class="detail" :title="item.comment" :key="j">
                                <div
                                    class="name"
                                    :class="{ on: `d${i}m${j}` == nowIndex }"
                                    @click="loadFrame(`d${i}m${j}`, items.viewToken, item.id)"
                                >
                                    {{ item.name }}
                                </div>
                                <div>{{ item.number }}</div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="item2D">
                <div class="title">
                    <span>批注</span>
                    <div class="newButton" v-if="!isEdit">
                        <a href="javascript:void(0)" :class="{ 'btn-disable2': isView }" @click="createAnnotation">添加批注</a>
                    </div>
                </div>
                <div class="content contentB" v-if="!isEdit">
                    <ul class="annotationlist" v-if="!isEdit" style="max-height:calc(100% - 352px)">
                        <li
                            v-for="(item, i) in annotationlist"
                            :title="item.comment"
                            @click="annotationGetImage(i, item)"
                            :class="{ on: item.isClick }"
                            :key="i"
                        >
                            <img :src="item.src" alt="" class="annotation-img" style="width:80px;height:60px" />
                            <div class="info">
                                <p class="name" v-if="item.comment.length > 0">{{ item.comment }}</p>
                                <p class="name" v-else>-</p>
                                <p>{{ item.time }}</p>
                                <p>图名：{{ item.name }}</p>
                                <p>图号：{{ item.number }}</p>
                            </div>
                            <h3 style="color:red">答疑：</h3>
                            <el-input type="textarea" v-if="item.isClick" v-model="nowAnswer" @blur="handleAnswer(item.comment)"></el-input>
                        </li>
                    </ul>
                </div>
                <div class="edit contentB" v-if="isEdit" :class="{ 'side-isedit': isEdit }">
                    <div class="annotation-brief">
                        <p>图名：{{ this.nowName }}</p>
                        <p>图号：{{ this.nowNumber }}</p>
                    </div>
                    <textarea placeholder="添加批注描述" v-model="comment"></textarea>
                    <a href="javascript:void(0)" class="btn btn-sm btn-primary" @click="annotationSave">保存</a>
                    <a href="javascript:void(0)" class="btn btn-sm btn-default" @click="annotationCancel">取消</a>
                </div>
            </div>
            <div class="mask" v-if="isView">
                <a href="javascript:void(0)" class="btn btn-exit" @click="maskExit">退出</a>
            </div>
        </div>
    </div>
</template>

<script>
import Vue from 'vue';
export default {
    data() {
        return {
            cHeight: null,
            viewToken: null,
            loaded: false,
            isEdit: false,
            isView: false,
            state: null,
            nowAnswer:null,
            comment: '',
            annotationlist: null,
            dwgViewer: {
                toolbar: null, // 工具条
                annotationManager: null, // annotation的绘制管理器
                annotationToolbar: null,
                annotationControl: null // 重写annotation的保存、取消
            },
            drawingFrame: null,
            isAllLoaded: false,
            nowIndex: null,
            nowName: null,
            nowNumber: null,
            listStorage: [[[]]],
            layerStatus: null,
            setListNew: []
        };
    },
    mounted() {
        var me = this;
        var fileId = me.$route.query.fileId
        me.setListNew = sessionStorage.getItem('answer');
        if (me.setListNew === null || me.setListNew === undefined) {
            me.setListNew = [];
        } else {
            me.setListNew = JSON.parse(me.setListNew);
        }
        
        var AccessToken = localStorage.getItem('token');
        var viewToken;
        this.$axios({
            method: 'get',
            url: 'http://localhost:8080/user/getModelViewToken?fileId='+fileId+'&AccessToken='+AccessToken
        })
            .then(res => {
                console.log(res)
            })
            .catch(err => {
                console.log(err);
            });
        viewToken = '10c649e8832743119d856e00ff9aea0e';
        var BimfaceLoaderConfig = new BimfaceSDKLoaderConfig();
        BimfaceLoaderConfig.viewToken = viewToken;
        BimfaceSDKLoader.load(BimfaceLoaderConfig, successCallback, failureCallback);

        function successCallback(databag) {
            // 获取DOM元素
            var dom4Show = document.getElementById('modelView');
            var WebDwgConfig = new Glodon.Bimface.Application.WebApplicationDrawingConfig();
            WebDwgConfig.domElement = dom4Show;
            //WebDwgConfig.Buttons = ['Home', "RectZoom", "DrawingMeasure", "FullScreen"];

            window.app = new Glodon.Bimface.Application.WebApplicationDrawing(WebDwgConfig);
            app.load(viewToken);
            window.viewer2D = app.getViewer();
            drawingViewExtend(databag, viewToken);
        }

        function failureCallback(error) {
            console.log(error);
        }

        function drawingViewExtend(databag, viewToken) {
            var viewerEvents = Glodon.Bimface.Viewer.ViewerDrawingEvent;
            viewer2D.addEventListener(viewerEvents.Loaded, function() {
                me.loaded = true;
                if (!me.drawingFrame) {
                    viewer2D.getDrawingFrame(function(data) {
                        me.drawingFrame = [
                            {
                                viewToken: viewToken,
                                name: databag.name,
                                model: data.data[0].frames
                            }
                        ];
                        viewer2D.destroy();
                        me.loadDwg();
                    });
                }
                //自适应屏幕大小
                window.onresize = function() {
                    viewer2D.resize(document.documentElement.clientWidth, document.documentElement.clientHeight - 40);
                };
                // 添加批注按钮
                var viewerDom = viewer2D.getRootElement();
                // me.dwgViewer.toolbar = viewerDom.querySelector('.bf-toolbar-bottom')
            });
        }
    },
    methods: {
        handleAnswer(value){
            var answer = JSON.parse(sessionStorage.getItem("answer"))
            for(let i=0;i<answer.length;i++){
                if(answer[i].comment===value){
                    answer[i].answer=this.nowAnswer
                    console.log(this.nowAnswer)
                }
            }
            console.log(answer)
            answer = JSON.stringify(answer)
            sessionStorage.setItem("answer",answer)
            this.nowAnswer = ''
        },
        loadDwg() {
            const me = this;
            var viewToken = '10c649e8832743119d856e00ff9aea0e';
            var BimfaceLoaderConfig = new BimfaceSDKLoaderConfig();
            BimfaceLoaderConfig.viewToken = viewToken;
            BimfaceSDKLoader.load(BimfaceLoaderConfig, successCallback, failureCallback);

            function successCallback(databag) {
                viewer2D.destroy();
                app.load(viewToken);
                viewer2D.addEventListener(Glodon.Bimface.Viewer.ViewerDrawingEvent.Loaded, function() {
                    if (!me.isAllLoaded) {
                        viewer2D.getDrawingFrame(function(data) {
                            const dwgFrame = {
                                viewToken: viewToken,
                                name: databag.name,
                                model: data.model
                            };
                            me.drawingFrame.push(dwgFrame);
                            me.isAllLoaded = true;
                        });
                        const loadViewToken = me.drawingFrame[0].viewToken;
                        const loadModel = me.drawingFrame[0].model[0].id;
                        me.loadFrame(`d0m0`, loadViewToken, loadModel);
                        console.log('drawingFrame', me.drawingFrame);
                    }
                    me.defaultAnnotation();
                });
            }
            function failureCallback(error) {
                console.log(error);
            }
        },
        loadFrame(index, viewToken, id) {
            const me = this;

            if (!me.isView) {
                if (me.isAllLoaded) {
                    const oldDwg = me.nowIndex.split('')[1];
                    const oldModel = me.nowIndex.split('')[3];
                    // me.saveLayers(oldDwg,oldModel);
                }
                me.nowIndex = index;

                viewer2D.destroy();
                app.loadFrame(viewToken, id);
                viewer2D.addEventListener(Glodon.Bimface.Viewer.ViewerDrawingEvent.Loaded, function() {
                    me.defaultAnnotation();
                    // if(!me.layerStatus) sessionStorage.layers = JSON.stringify(spliteLayers);
                    const dwgIndex = me.nowIndex.split('')[1];
                    const modelIndex = me.nowIndex.split('')[3];
                    me.nowName = me.drawingFrame[dwgIndex].model[modelIndex].name;
                    me.nowNumber = me.drawingFrame[dwgIndex].model[modelIndex].number;
                    // if (me.isAllLoaded) me.setLayers(dwgIndex, modelIndex)
                });
            }
        },

        // 批注
        defaultAnnotation() {
            const me = this;
            // if(!me.listStorage) sessionStorage.annotationList = JSON.stringify(spliteAnnotation);
            me.clearToolDom();
            me.dwgViewer.annotationManager = null;
            if (!me.dwgViewer.annotationManager) {
                var config = new Glodon.Bimface.Plugins.Annotation.AnnotationToolbarConfig();
                config.viewer = viewer2D;
                var annotationToolbar = new Glodon.Bimface.Plugins.Annotation.AnnotationToolbar(config);

                me.dwgViewer.annotationToolbar = annotationToolbar;
                me.dwgViewer.annotationManager = annotationToolbar.getAnnotationManager();
                me.defaultAnnotationList();
            }
        },
        defaultAnnotationList() {
            const me = this;
            me.annotationlist = [];
            const dwgIndex = me.nowIndex.split('')[1];
            const modelIndex = me.nowIndex.split('')[3];
            if (sessionStorage.annotationList) {
                me.listStorage = JSON.parse(sessionStorage.annotationList);
                // 增加获取图层状态
                // var layerStatus = me.listStorage[dwgIndex][modelIndex]
                if (me.listStorage[dwgIndex][modelIndex] === null || me.listStorage[dwgIndex][modelIndex] === undefined) return;
                me.listStorage[dwgIndex][modelIndex].forEach(item => {
                    me.dwgViewer.annotationManager.setAnnotationList(item.status);
                    me.dwgViewer.annotationManager.createSnapshot(function(data) {
                        var date = new Date();
                        var seperator1 = '-';
                        var seperator2 = ':';
                        var month = date.getMonth() + 1;
                        var strDate = date.getDate();
                        let currentdate =
                            date.getFullYear() +
                            seperator1 +
                            month +
                            seperator1 +
                            strDate +
                            ' ' +
                            date.getHours() +
                            seperator2 +
                            date.getMinutes() +
                            seperator2 +
                            date.getSeconds();
                        let _img;
                        item.img ? (_img = item.img) : (_img = data);
                        var obj = {
                            comment: item.comment,
                            time: currentdate,
                            src: _img,
                            state: item.status,
                            isClick: false,
                            name: me.nowName,
                            number: me.nowNumber
                        };
                        me.annotationlist.push(obj);
                    });
                });
            }

            me.annotationCancel();
        },
        createAnnotation: function() {
            if (!this.isView) {
                this.isEdit = true;
                this.state = [];
                this.comment = '';
                this.changeModel(1);
                this.dwgViewer.annotationToolbar.show();
            }
        },
        changeModel: function(num) {
            if (num == 0) {
                app.getToolbar('MainToolbar').show();
            } else {
                app.getToolbar('MainToolbar').hide();
            }
        },
        annotationSave: function() {
            var me = this;
            let _state = me.dwgViewer.annotationManager.getCurrentState();
            if (_state.annotationList.length == 0) {
                const emptyObj = {
                    rotation: 0,
                    markupType: 'Cross',
                    drawPoints: [0, 0],
                    strokeStyle: 'rgba(0,0,0,0)',
                    lineWidth: 0,
                    bNeedHitByBbox: false,
                    drawEnd: true,
                    markupId: ''
                };
                _state.annotationList.push(emptyObj);
            }
            me.dwgViewer.annotationManager.createSnapshot(function(data) {
                var date = new Date();
                var seperator1 = '-';
                var seperator2 = ':';
                var month = date.getMonth() + 1;
                var strDate = date.getDate();
                let currentdate =
                    date.getFullYear() +
                    seperator1 +
                    month +
                    seperator1 +
                    strDate +
                    ' ' +
                    date.getHours() +
                    seperator2 +
                    date.getMinutes() +
                    seperator2 +
                    date.getSeconds();
                let _img = data;
                var obj = {
                    comment: me.comment,
                    time: currentdate,
                    src: _img,
                    state: _state,
                    isClick: false,
                    name: me.nowName,
                    number: me.nowNumber
                };
                me.annotationlist.push(obj);

                const dwgIndex = me.nowIndex.split('')[1];
                const modelIndex = me.nowIndex.split('')[3];
                var storageObj = {
                    comment: me.comment,
                    img: _img,
                    time: currentdate,
                    status: _state,
                    name: me.nowName,
                    number: me.nowNumber
                };

                if (me.listStorage[dwgIndex][modelIndex] === undefined || me.listStorage[dwgIndex][modelIndex] === null) {
                    me.listStorage[dwgIndex][modelIndex] = [];
                    console.log(me.listStorage[dwgIndex][modelIndex]);
                    me.listStorage[dwgIndex][modelIndex].push(storageObj);
                } else {
                    me.listStorage[dwgIndex][modelIndex].push(storageObj);
                }
                sessionStorage.annotationList = JSON.stringify(me.listStorage);
            });
            var newObj = {
                number: me.nowNumber,
                name: me.nowName,
                comment: me.comment,
                answer: '',
                result: ''
            };
            me.setListNew.push(newObj);
            sessionStorage.setItem('answer', JSON.stringify(me.setListNew));
            me.annotationCancel();

            console.log(me.listStorage);
        },

        annotationCancel: function() {
            this.dwgViewer.annotationManager.endDrawing();
            this.isEdit = false;
            this.changeModel(0);
            document.querySelector('.bf-annotation').addClass('bf-hide');
        },
        clearToolDom() {
            let markupVirtual = document.querySelector('#markupVirtual');
            if (markupVirtual) markupVirtual.parentNode.removeChild(markupVirtual);
            let control = document.querySelector('.bf-toolbar-control');
            if (control) control.parentNode.removeChild(control);
            let annotation = document.querySelector('.bf-annotation');
            if (annotation) annotation.parentNode.removeChild(annotation);
        },
        annotationGetImage: function(i, data) {
            const me = this;
            const dwgIndex = me.nowIndex.split('')[1];
            const modelIndex = me.nowIndex.split('')[3];
            let image;
            if (!me.isEdit) {
                me.isView = true;
                me.clearListStyle();
                me.changeModel(1);
                data.isClick = true;
                me.dwgViewer.annotationManager.setState(data.state);
                if (!me.listStorage[dwgIndex][modelIndex][i].img) {
                    me.dwgViewer.annotationManager.createSnapshot(function(snapshot) {
                        image = snapshot;
                        const copyList = me.annotationlist;
                        copyList[i].src = image;
                        me.annotationList = copyList;
                        const imgs = document.querySelectorAll('.annotation-img');
                        imgs[i].setAttribute('src', image);
                    });
                }
            }
        },
        clearListStyle: function() {
            for (let i = 0; i < this.annotationlist.length; i++) {
                this.annotationlist[i].isClick = false;
            }
        },
        maskExit: function() {
            this.isView = false;
            this.clearListStyle();
            this.changeModel(0);
            this.dwgViewer.annotationManager.startDrawing();
            this.dwgViewer.annotationManager.endDrawing();
        }
    }
};
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}
#lzx_container {
    display: flex;
    height: 100%;
    overflow: hidden;
    background: #eee;
}
#modelView {
    width: 82%;
    height: 100%;
    background-color: #ddd;
}
#side2D {
    width: 18%;
    height: 100%;
    overflow: hidden;
}
canvas {
    left: 0 !important;
}

#side2D {
    width: 18%;
    margin: 0 0 10px 0;
}

#side2D .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 8px 10px;
    height: 24px;
    line-height: 24px;
    border-left: 4px solid #32d3a6;
}

#side2D .content {
    height: 30vh;
    width: 100%;
    background-color: #fff;
    overflow: auto;
}

#side2D .contentB {
    height: 43vh;
    overflow: scroll;
}
.side-isedit {
    height: 93vh !important;
}
.content::-webkit-scrollbar {
    /*高宽分别对应横竖滚动条的尺寸*/
    width: 10px;
    height: 10px;
}
/* 滚动条中的小方块处理 */
.content::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #eee;
}
/* 滚动条滚动的轨道 */
.content::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 10px;
    background: #fff;
}
#side2D .title span {
    margin-left: 6px;
    font-size: 16px;
}

.newButton {
    box-sizing: border-box;
    padding: 2px;
    padding-left: 0;
    text-align: center;
    width: 80px;
    border-radius: 3px;
    border: none;
    background: #11dab7;
    font-size: 14px;
}

.newButton a {
    color: #fff;
    text-decoration: none;
}

.drawinglist {
    padding: 5px 15px;
    color: #999;
    list-style: none;
    text-align: left;
    font-size: 14px;
    line-height: 24px;
}
.detail {
    padding-left: 20px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.drawinglist .on {
    color: #32d5a7 !important;
}
.drawinglist .name {
    cursor: pointer;
    color: #333;
}
.annotationlist li {
    position: relative;
    overflow: hidden;
    border-bottom: 1px solid #ddd;
    padding: 8px 10px 8px 100px;
    box-sizing: border-box;
    color: #999;
    border-left: 2px solid #eee;
    font-size: 12px;
    cursor: pointer;
}
.annotationlist li.on {
    height: auto;
    background-color: #e4fff7;
    border-left: 2px solid #11dab7;
}

.annotationlist li img {
    position: absolute;
    left: 10px;
    width: 80px;
    height: 50px;
    border: 1px solid #ddd;
    background-color: #fff;
}
.annotationlist li .name {
    color: #333;
    font-size: 14px;
    line-height: 20px;
}
.annotationlist li .info p {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    text-align: left;
}
.annotationlist li.on .info p {
    white-space: unset !important;
}
.edit {
    border-bottom: 1px solid #ccc;
    padding: 10px;
    background-color: #fff;
}

.annotation-brief {
    color: #999;
}
.annotation-brief p {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    text-align: left;
    font-size: 14px;
    line-height: 24px;
}
.edit textarea {
    border: 1px solid #ddd;
    box-sizing: border-box;
    width: 100%;
    margin: 5px 0;
    height: 100px;
    resize: none;
    padding: 5px;
    font-size: 14px;
    outline: none;
}
.edit textarea:active {
    outline: #11dab7 !important;
}
.side .edit a {
    display: inline-block;
    vertical-align: middle;
    margin-right: 8px;
}
.btn.btn-sm {
    padding: 0 20px;
    line-height: 28px;
}
.btn.btn-primary {
    background: #11dab7;
    color: #fff;
}
.btn-sm {
    height: 28px;
}
.btn {
    text-align: center;
    border: none;
    border-radius: 3px;
    outline: none;
    box-sizing: border-box;
    cursor: pointer;
    float: left;
    margin-right: 4px;
}
a.btn {
    text-decoration: none !important;
    color: #11dab7;
}

.btn.btn-default {
    background: transparent;
    color: #32d3a6;
    border: 1px solid #32d3a6;
}
.btn-exit {
    border: 1px solid #333;
    background-color: hsla(0, 0%, 7%, 0.88);
    position: absolute;
    left: 40%;
    bottom: 10px;
    transform: translate(-40%);
    padding: 10px 15px;
    width: 100px;
    text-align: center;
    color: #fff !important;
    z-index: 199;
}
</style>
<style>
.content {
    padding-right: 0px !important;
}
.el-textarea__inner{
    padding-left: 6px;
}
</style>
